

package cn.shengchao.dubbo.bi;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.shengchao.base.utils.SecureUtils;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeNodeInfo;
import cn.shengchao.examstar.distribute.infrastrure.po.DistributeUserBank;
import cn.shengchao.examstar.distribute.infrastrure.query.DistributeAmountQuery;
import cn.shengchao.examstar.distribute.infrastrure.service.*;
import cn.shengchao.examstar.distribute.model.DistributeNodeRoleChainExistModel;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeNodeRoleChainDomainService;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeNodeRoleChainExistLoader;
import cn.shengchao.examstar.rpc.base.PageResult;
import cn.shengchao.examstar.distribute.infrastrure.query.DistributeUserSaleDetailQuery;
import cn.shengchao.examstar.distribute.infrastrure.vo.DistributeContentUserGroup;
import cn.shengchao.examstar.distribute.infrastrure.vo.DistributeSaleUserGroup;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeContentRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeDataStatusEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeSaleRoleEnum;
import cn.shengchao.examstar.rpc.distribute.enums.DistributeTypeEnum;
import cn.shengchao.examstar.rpc.uddsys.bi.PlatformUserArchQueryBI;
import cn.shengchao.examstar.rpc.uddsys.req.DistributeUserInvitePageQuery;
import cn.shengchao.examstar.rpc.uddsys.req.DistributeUserProfitDetailPage;
import cn.shengchao.examstar.rpc.uddsys.req.PlatformDistributeUserPageQuery;
import cn.shengchao.examstar.rpc.uddsys.resp.*;
import cn.shengchao.examstart.user.acl.adapters.repositories.UserRepository;
import cn.shengchao.examstart.user.domain.entity.User;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import net.dreamlu.mica.core.utils.DesensitizationUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * @program: examstarapi
 * @description: 平台分销用户的查询服务
 * @author: Xiong weiqiang
 * @create: 2025-03-31 16:23
 */
@DubboService
public class PlatformUserArchQueryBIService implements PlatformUserArchQueryBI {
    @Autowired
    private DistributeNodeRoleChainService distributeNodeRoleChainService;
    @Autowired
    private DistributeNodeRoleChainDomainService distributeNodeRoleChainDomainService;
    @Autowired
    private DistributeNodeRoleChainExistLoader distributeNodeRoleChainExistLoader;
    @Autowired
    private DistributeUserBankService distributeUserBankService;
    @Autowired
    DistributeOrderTaskSaleService distributeOrderTaskSaleService;
    @Autowired
    UserRepository userRepository;
    @Autowired
    DistributeOrderTaskContentService distributeOrderTaskContentService;
    @Autowired
    DistributeUserInviteService distributeUserInviteService;
    @Autowired
    DistributeNodeInfoService distributeNodeInfoService;

//    @Override
//    public List<DistributeUserMonthStaticVo> listMonthStaticListSortForUpLevelUser(Long userId, Integer distributeType) {
//        PlatformDistributeUserStatisticQuery saleAmountQuery=new PlatformDistributeUserStatisticQuery();
//        saleAmountQuery.setUpLevelUserId(userId);
//        saleAmountQuery.setStartDistributeTime(DateUtil.beginOfMonth(new Date()).toJdkDate());
//        saleAmountQuery.setEndDistributeTime(DateUtil.endOfMonth(new Date()).toJdkDate());
//
//        if (distributeType== DistributeTypeEnum.TYPE_SALE.getType()){
//            List<DistributeUserMonthStaticVo> list=distributeOrderTaskSaleService.listStaticListSortForUpLevelUser(saleAmountQuery);
//            return list;
//        }else if (distributeType== DistributeTypeEnum.TYPE_CTPD.getType()){
//            List<DistributeUserMonthStaticVo> list=distributeOrderTaskContentService.listStaticListSortForUpLevelUser(saleAmountQuery);
//            return list;
//        }
//        return List.of();
//    }

    @Override
    public PageResult<DistributeUserVo> queryPlatformUserArchPage(PlatformDistributeUserPageQuery platformDistributeUserPageQuery) {
        PageResult<DistributeUserVo> pageResult= distributeNodeRoleChainService.queryPlatformUserArchPage(platformDistributeUserPageQuery);
        if (CollUtil.isNotEmpty(pageResult.getList())){
            List<DistributeUserVo> list=pageResult.getList();
            List<Long> userIds=list.stream().map(DistributeUserVo::getUserId).toList();
            List<DistributeNodeInfo> nodeInfoList=distributeNodeInfoService
                    .list(Wrappers.<DistributeNodeInfo>lambdaQuery().in(DistributeNodeInfo::getUserId,userIds)
                            .eq(DistributeNodeInfo::getDistributeType, platformDistributeUserPageQuery.getDistributeType())
                            .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                    );

            if (platformDistributeUserPageQuery.getDistributeType()== DistributeTypeEnum.TYPE_SALE.getType()){
                List<CompletableFuture<DistributeSaleUserGroup>> completableFutures = nodeInfoList.stream()
                        .map(item -> CompletableFuture.supplyAsync(() -> {
                            DistributeAmountQuery saleAmountQuery=new DistributeAmountQuery();
                            saleAmountQuery.setStatus(List.of("1"));
//                            if (platformDistributeUserPageQuery.getCreateTimeStart()==null||platformDistributeUserPageQuery.getCreateTimeEnd()==null) {
//                                saleAmountQuery.setStartDistributeTime(DateUtil.beginOfMonth(new Date()).toJdkDate());
//                                saleAmountQuery.setEndDistributeTime(DateUtil.endOfMonth(new Date()).toJdkDate());
//                            }else {
//                                saleAmountQuery.setStartDistributeTime(platformDistributeUserPageQuery.getCreateTimeStart());
//                                saleAmountQuery.setEndDistributeTime(platformDistributeUserPageQuery.getCreateTimeEnd());
//                            }
                            saleAmountQuery.setStartDistributeTime(platformDistributeUserPageQuery.getCreateTimeStart());
                            saleAmountQuery.setEndDistributeTime(platformDistributeUserPageQuery.getCreateTimeEnd());
                            saleAmountQuery.setSaleUserId(item.getUserId());
                            saleAmountQuery.setDistributeRoleCode(item.getDistributeRoleCode());
                            if (DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(item.getDistributeRoleCode())){
                                saleAmountQuery.setUpLevelUserId(item.getAdminUserId());
                            }
                            DistributeSaleUserGroup saleUserGroup=distributeOrderTaskSaleService.getSaleAmountForDistributeUser(saleAmountQuery);
                            if (saleUserGroup ==null){
                                saleUserGroup=new DistributeSaleUserGroup();
                                saleUserGroup.setDistributeUserId(item.getUserId());
                                saleUserGroup.setAmount(BigDecimal.ZERO);
                                saleUserGroup.setOrderAmount(BigDecimal.ZERO);
                            }
                            return saleUserGroup;
                        }))
                        .toList();
                CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join();
                List<DistributeSaleUserGroup> userMonthAmountList=completableFutures.stream().map(CompletableFuture::join).toList();
                if (CollUtil.isNotEmpty(userMonthAmountList)){
                    Map<Long, BigDecimal> monthProfitMap=userMonthAmountList.stream().collect(HashMap::new, (k, v) -> k.put(v.getDistributeUserId(), v.getAmount()), HashMap::putAll);
                    Map<Long, BigDecimal> monthorderMap=userMonthAmountList.stream().collect(HashMap::new, (k, v) -> k.put(v.getDistributeUserId(), v.getOrderAmount()), HashMap::putAll);
                    list.forEach(item->{
                        item.setMonthSumAmount(monthProfitMap.getOrDefault(item.getUserId(),BigDecimal.ZERO));
                        item.setOrderSumAmount(monthorderMap.getOrDefault(item.getUserId(),BigDecimal.ZERO));
                    });
                }else {
                    list.forEach(item->{
                        item.setMonthSumAmount(BigDecimal.ZERO);
                        item.setOrderSumAmount(BigDecimal.ZERO);
                    });
                }
            }else if (platformDistributeUserPageQuery.getDistributeType()== DistributeTypeEnum.TYPE_CTPD.getType()){
                List<CompletableFuture<DistributeContentUserGroup>> completableFutures = nodeInfoList.stream()
                        .map(item -> CompletableFuture.supplyAsync(() -> {
                            DistributeAmountQuery saleAmountQuery=new DistributeAmountQuery();
                            saleAmountQuery.setStatus(List.of("1"));
//                            if (platformDistributeUserPageQuery.getCreateTimeStart()==null||platformDistributeUserPageQuery.getCreateTimeEnd()==null) {
//                                saleAmountQuery.setStartDistributeTime(DateUtil.beginOfMonth(new Date()).toJdkDate());
//                                saleAmountQuery.setEndDistributeTime(DateUtil.endOfMonth(new Date()).toJdkDate());
//                            }else {
//                                saleAmountQuery.setStartDistributeTime(platformDistributeUserPageQuery.getCreateTimeStart());
//                                saleAmountQuery.setEndDistributeTime(platformDistributeUserPageQuery.getCreateTimeEnd());
//                            }
                            saleAmountQuery.setStartDistributeTime(platformDistributeUserPageQuery.getCreateTimeStart());
                            saleAmountQuery.setEndDistributeTime(platformDistributeUserPageQuery.getCreateTimeEnd());
                            saleAmountQuery.setSaleUserId(item.getUserId());
                            saleAmountQuery.setDistributeRoleCode(item.getDistributeRoleCode());
                            if (DistributeContentRoleEnum.ROLE_CTPD_EMP.getCode().equals(item.getDistributeRoleCode())){
                                saleAmountQuery.setUpLevelUserId(item.getAdminUserId());
                            }
                            DistributeContentUserGroup contentUserGroup=distributeOrderTaskContentService.getContentAmountForDistributeUser(saleAmountQuery);
                            if (contentUserGroup ==null){
                                contentUserGroup=new DistributeContentUserGroup();
                                contentUserGroup.setDistributeUserId(item.getUserId());
                                contentUserGroup.setAmount(BigDecimal.ZERO);
                                contentUserGroup.setOrderAmount(BigDecimal.ZERO);
                            }
                            return contentUserGroup;
                        }))
                        .toList();
                CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join();
                List<DistributeContentUserGroup> userMonthAmountList=completableFutures.stream().map(CompletableFuture::join).toList();
                if (CollUtil.isNotEmpty(userMonthAmountList)){
                    Map<Long, BigDecimal> monthProfitMap=userMonthAmountList.stream().collect(HashMap::new, (k, v) -> k.put(v.getDistributeUserId(), v.getAmount()), HashMap::putAll);
                    Map<Long, BigDecimal> monthorderMap=userMonthAmountList.stream().collect(HashMap::new, (k, v) -> k.put(v.getDistributeUserId(), v.getOrderAmount()), HashMap::putAll);
                    list.forEach(item->{
                        item.setMonthSumAmount(monthProfitMap.getOrDefault(item.getUserId(),BigDecimal.ZERO));
                        item.setOrderSumAmount(monthorderMap.getOrDefault(item.getUserId(),BigDecimal.ZERO));
                    });
                }else {
                    list.forEach(item->{
                        item.setMonthSumAmount(BigDecimal.ZERO);
                        item.setOrderSumAmount(BigDecimal.ZERO);
                    });
                }
            }
            List<DistributeUserBank> bankList=distributeUserBankService.list(Wrappers.lambdaQuery(DistributeUserBank.class).in(DistributeUserBank::getUserId, userIds).eq(DistributeUserBank::getDistributeType, platformDistributeUserPageQuery.getDistributeType()));
            if (CollUtil.isNotEmpty(bankList)){
                Map<Long, DistributeUserBank> map=bankList.stream().collect(HashMap::new, (k, v) -> k.put(v.getUserId(), v), HashMap::putAll);
                list.forEach(item->{
                    DistributeUserBank bank=map.getOrDefault(item.getUserId(),null);
                    if (bank!=null){
                        item.setCardNo(bank.getCardNo());
                    }
                });
            }
            pageResult.setList(list);
        }
        return pageResult;
    }

    @Override
    public List<DistributeUserProfitDetailVo> selectDistributeUserMonthProfitDetailList(Long userId,Integer distributeType) {
        DistributeUserSaleDetailQuery distributeUserSaleDetailQuery=new DistributeUserSaleDetailQuery();
        distributeUserSaleDetailQuery.setDistributeUserId(userId);
        distributeUserSaleDetailQuery.setStartDistributeTime(DateUtil.beginOfMonth(new Date()).toJdkDate());
        distributeUserSaleDetailQuery.setEndDistributeTime(DateUtil.endOfMonth(new Date()).toJdkDate());
        if (distributeType== DistributeTypeEnum.TYPE_SALE.getType()){
            List<DistributeUserProfitDetailVo> list=null;
            DistributeNodeRoleChainExistModel existModel=distributeNodeRoleChainExistLoader.loadModelByUserId(userId, DistributeTypeEnum.TYPE_SALE.getType());
            if (existModel.getDistributeNodeInfo().getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())){
                //设置员工的当前上级
                distributeUserSaleDetailQuery.setUpLevelUserId(existModel.getUpLevelNodeInfo().getUserId());
                list=distributeOrderTaskSaleService.getDistributeEmployeeContributeDetailList(distributeUserSaleDetailQuery);
                return list;
            }else {
                list=distributeOrderTaskSaleService.getDistributeUserProfitDetailList(distributeUserSaleDetailQuery);
            }
            return list;
        }else if (distributeType== DistributeTypeEnum.TYPE_CTPD.getType()){
            List<DistributeUserProfitDetailVo> list=null;
            DistributeNodeRoleChainExistModel existModel=distributeNodeRoleChainExistLoader.loadModelByUserId(userId, DistributeTypeEnum.TYPE_CTPD.getType());
            if (existModel.getDistributeNodeInfo().getDistributeRoleCode().equals(DistributeContentRoleEnum.ROLE_CTPD_EMP.getCode())){
                //设置员工的当前上级
                distributeUserSaleDetailQuery.setUpLevelUserId(existModel.getUpLevelNodeInfo().getUserId());
                list=distributeOrderTaskContentService.getDistributeEmployeeContributeDetailList(distributeUserSaleDetailQuery);
                return list;
            }else {
                list=distributeOrderTaskContentService.getDistributeUserProfitDetailList(distributeUserSaleDetailQuery);
                return list;
            }
        }
        return List.of();
    }

    @Override
    public PageResult<DistributeUserInviteVo> queryDistributeUserInvitePage(DistributeUserInvitePageQuery distributeUserInvitePageQuery) {
        List<Long> chainUserIds=new ArrayList<>();

        if (distributeUserInvitePageQuery.getDistributeUserId()!=null){
            chainUserIds.add(distributeUserInvitePageQuery.getDistributeUserId());
            DistributeNodeInfo distributeNodeInfo=distributeNodeInfoService.getOne(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                    .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE.getType())
                    .eq(DistributeNodeInfo::getUserId, distributeUserInvitePageQuery.getDistributeUserId())
                    .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
            );
            if (distributeNodeInfo!=null&&distributeUserInvitePageQuery.getDistributeUserId()!=null&&distributeUserInvitePageQuery.getIncludeLowLevel()!=null&&distributeUserInvitePageQuery.getIncludeLowLevel()==1){
                Map<Long,Set<Long>> lowNodeUserIdMap=distributeNodeRoleChainDomainService.getLowNodeUserIds(DistributeTypeEnum.TYPE_SALE.getType(), List.of(distributeUserInvitePageQuery.getDistributeUserId()), distributeNodeInfo.getDistributeRoleCode());
                lowNodeUserIdMap.values().forEach(chainUserIds::addAll);
            }
            distributeUserInvitePageQuery.setDistributeChainUserIds(chainUserIds);
        }

        PageResult<DistributeUserInviteVo> pageResult=distributeUserInviteService.queryDistributeUserInvitePage(distributeUserInvitePageQuery);
        if (CollUtil.isNotEmpty(pageResult.getList())){
            List<Long> distributeUserIds=pageResult.getList().stream().map(DistributeUserInviteVo::getDistributeUserId).toList();
            List<User> userList=userRepository.getUserList(distributeUserIds);
            List<DistributeNodeInfo> distributeNodeInfos=distributeNodeInfoService.list(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                    .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE.getType())
                    .in(DistributeNodeInfo::getUserId, distributeUserIds)
                    .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
            );
            Map<Long,User> userMap=userList.stream().collect(HashMap::new,(k,v)->k.put(v.getId(),v),HashMap::putAll);
            Map<Long,DistributeNodeInfo> distributeNodeInfoMap=distributeNodeInfos.stream().collect(HashMap::new,(k,v)->k.put(v.getUserId(),v),HashMap::putAll);
            pageResult.getList().forEach(item->{
                String phone=SecureUtils.decryptFieldByAes(item.getStudentPhone());
               item.setStudentPhone(DesensitizationUtil.mobileNo(phone));
                if (item.getDistributeUserId()==0){
                    item.setDistributeUserPhone("平台");
                    item.setDistributeUserName("平台");
                }else {
                    User user=userMap.get(item.getDistributeUserId());
                    DistributeNodeInfo distributeNodeInfo1=distributeNodeInfoMap.get(item.getDistributeUserId());
                    item.setDistributeUserPhone(user==null?"": DesensitizationUtil.mobileNo(user.getPhone()));
                    item.setDistributeUserName(distributeNodeInfo1!=null? distributeNodeInfo1.getFullName():(user==null?"":user.getName()));
                }
            });
        }
        return pageResult;
    }

    @Override
    public List<DistributeUserInviteSelectVo> listDistributeUserInviteSelectVo(String searchValue) {
        return distributeNodeInfoService.selectDistributeUserInviteSelectVo(searchValue);
    }

    @Override
    public PageResult<DistributeUserProfitDetailVo> selectDistributeUserProfitDetailPageList(DistributeUserProfitDetailPage detailPage) {
        Page<Object> page=null;
        Long userId=detailPage.getDistributeUserId();
        Integer distributeType=detailPage.getDistributeType();
        DistributeUserSaleDetailQuery distributeUserSaleDetailQuery=new DistributeUserSaleDetailQuery();
        distributeUserSaleDetailQuery.setDistributeUserId(userId);
//        if (detailPage.getStartTime()==null||detailPage.getEndTime()==null){
//            distributeUserSaleDetailQuery.setStartDistributeTime(DateUtil.beginOfMonth(new Date()).toJdkDate());
//            distributeUserSaleDetailQuery.setEndDistributeTime(DateUtil.endOfMonth(new Date()).toJdkDate());
//        }
        List<DistributeUserProfitDetailVo> list=null;
        if (distributeType== DistributeTypeEnum.TYPE_SALE.getType()){
            DistributeNodeRoleChainExistModel existModel=distributeNodeRoleChainExistLoader.loadModelByUserId(userId, DistributeTypeEnum.TYPE_SALE.getType());
            page=PageHelper.startPage(detailPage.getPage(), detailPage.getSize());
            if (existModel.getDistributeNodeInfo().getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())){
                distributeUserSaleDetailQuery.setUpLevelUserId(existModel.getUpLevelNodeInfo().getUserId());
                list=distributeOrderTaskSaleService.getDistributeEmployeeContributeDetailList(distributeUserSaleDetailQuery);
            }else {
                list=distributeOrderTaskSaleService.getDistributeUserProfitDetailList(distributeUserSaleDetailQuery);
            }
        }else if (distributeType== DistributeTypeEnum.TYPE_CTPD.getType()){
            DistributeNodeRoleChainExistModel existModel=distributeNodeRoleChainExistLoader.loadModelByUserId(userId, DistributeTypeEnum.TYPE_CTPD.getType());
            page=PageHelper.startPage(detailPage.getPage(), detailPage.getSize());
            if (existModel.getDistributeNodeInfo().getDistributeRoleCode().equals(DistributeContentRoleEnum.ROLE_CTPD_EMP.getCode())){
                distributeUserSaleDetailQuery.setUpLevelUserId(existModel.getUpLevelNodeInfo().getUserId());
                list=distributeOrderTaskContentService.getDistributeEmployeeContributeDetailList(distributeUserSaleDetailQuery);
            }else {
                list=distributeOrderTaskContentService.getDistributeUserProfitDetailList(distributeUserSaleDetailQuery);
            }
        }
        if (page!=null){
            return PageResult.of(page.getTotal(), list);
        }else {
            return PageResult.of(0L, list);
        }

    }
}